<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import {
  ElDialog,
  ElTooltip,
  ElSelect,
  ElInput,
  ElOption,
  ElButton,
  ElImage,
  ElDatePicker
} from 'element-plus'
import { Table } from '@/components/Table'
import {
  getPasCountApi,
  delTicketsApi,
  getConditionTableListApi,
  getPasNameApi
} from '@/api/dashboard/ticket'
import { useTable } from '@/hooks/web/useTable'
import { reactive, ref, unref, onMounted, onUnmounted } from 'vue'
import { useEventBus } from '@/hooks/event/useEventBus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { useIcon } from '@/hooks/web/useIcon'
import RiskSettingDialog from './components/RiskSettingDialog.vue'
import { Search, Tools } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
import dayjs from 'dayjs'
const PATH_URL = import.meta.env.VITE_API_BASE_PATH

defineOptions({
  name: 'Ticket'
})
const userStore = useUserStore()
const refreshIcon = useIcon({ icon: 'vi-ep:refresh-left' })
const ids = ref<any[]>([])
const bankOption = ref<any[]>([])
const nameOption = ref<any[]>([])
const dialogVisible = ref(false)
const viewerVisible = ref(false)
const viewerList = ref<any[]>([])
const isBack = ref(false)

const searchParams = ref({
  type: 1,
  condition: '',
  accountName: userStore.getUserInfo?.accountName
    ? userStore.getUserInfo?.accountName.split(',')
    : [],
  time: []
})

const listTotal = ref(0)

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const [beginTime = '', endTime = ''] = searchParams.value.time || []
    const res = await getConditionTableListApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams),
      accountName: searchParams.value.accountName.join(','),
      beginTime,
      endTime
    })
    listTotal.value = res.data.data.total
    return {
      list: res.data.data.list,
      total: res.data.data.total
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

useEventBus({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

const onViewer = (row: any) => {
  viewerList.value = [[...row.tkImgUrl.split(',')], row.subImgs ? [...row.subImgs.split(',')] : []]
  viewerVisible.value = true
}

const tableSelectionChange = (val) => {
  ids.value = val
}

const getTotal = async () => {
  const [beginTime = '', endTime = ''] = searchParams.value.time || []
  const res = await getConditionTableListApi({
    pageIndex: unref(currentPage),
    pageSize: unref(pageSize),
    ...unref(searchParams),
    accountName: searchParams.value.accountName.join(','),
    beginTime,
    endTime
  })
  if (res.data.data.total != listTotal.value) {
    getList(false)
  }
}

const selectChangeName = (e) => {
  const userInfo = userStore.getUserInfo
  if (userInfo) {
    userStore.setUserInfo({
      ...userInfo,
      accountName: e.join(',')
    })
  }
}

let timer: any = null

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

onMounted(() => {
  getPasCountApi().then((res) => {
    if (res.code != '200') return
    bankOption.value = res.data
  })
  getPasNameApi().then((res) => {
    if (res.code != '200') return
    nameOption.value = res.data.map((o) => ({
      ...o,
      id: o.accountName
    }))
  })

  timer = setInterval(() => {
    getTotal()
  }, 3000)
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection',
      reserveSelection: true
    }
  },
  {
    field: 'sysAddtime',
    label: '识别时间'
  },
  {
    field: 'paAccountName',
    label: '识别户',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'tkNumber',
    label: '票号后六位',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      span: 24,
      slots: {
        default: (data: any) => {
          return <div>{data.row.tkNumber.slice(data.row.tkNumber.length - 6)}</div>
        }
      }
    }
  },
  {
    field: 'tkChangeName',
    label: '承兑人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'tkAmount',
    label: '票面金额(万)',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'tkTimeOver',
    label: '到期日',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'xiaci',
    label: '瑕疵',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      span: 24,
      'show-overflow-tooltip': false,
      slots: {
        default: (data: any) => {
          if (!data.row.xcList) return <span>{data.row.xiaci}</span>
          return data.row.xcList.map((o) => {
            let tips = ''
            o.singleTips.split(';').map((p, i) => {
              if (p) {
                tips += `<P>&nbsp &nbsp${i + 1}、${p}</p>`
              }
            })
            return (
              <ElTooltip
                content={`<div><p><strong><b>瑕疵：${o.singleTipsTitle}</b></strong></p><div>${tips}</div></div>`}
                placement="top"
                raw-content
              >
                <>
                  {o.single ? (
                    <div class="flex items-center mt-2">
                      <Icon icon="vi-ant-design:exclamation-circle-filled" color="#E6A23C" />
                      <div class="ml-1">{o.single}</div>
                    </div>
                  ) : (
                    '--'
                  )}
                </>
              </ElTooltip>
            )
          })
        }
      }
    }
  },
  {
    field: 'bsCount',
    label: '背书手数',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      span: 24,
      'show-overflow-tooltip': false,
      slots: {
        default: (data: any) => {
          return (
            <div class="flex items-center">
              <div class="mr-1" style={{ color: 'red' }}>
                {data.row.bsCount}
              </div>
            </div>
          )
        }
      }
    }
  },
  {
    field: 'lastBs',
    label: '最后一手背书',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'single',
    label: '风险',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      span: 24,
      'show-overflow-tooltip': false,
      slots: {
        default: (data: any) => {
          if (!data.row.jgList) return <span>--</span>
          return data.row.jgList.map((o) => {
            let tips = ''
            o.singleTips.split(';').map((p, i) => {
              if (p) {
                tips += `<P>&nbsp &nbsp${i + 1}、${p}</p>`
              }
            })
            return (
              <ElTooltip
                content={`<div><p><strong><b>风险：${o.singleTipsTitle}</b></strong></p><div>${tips}</div></div>`}
                placement="top"
                raw-content
              >
                <>
                  {o.single ? (
                    <div class="flex items-center mt-2">
                      <Icon icon="vi-ant-design:exclamation-circle-filled" color="#E6A23C" />
                      <div class="ml-1">{o.single}</div>
                    </div>
                  ) : (
                    '--'
                  )}
                </>
              </ElTooltip>
            )
          })
        }
      }
    }
  },
  {
    field: 'action',
    width: '100px',
    label: '操作',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton
                onClick={() => {
                  isBack.value = false
                  onViewer(data.row)
                }}
                size="small"
                link
                type="primary"
              >
                查看票面
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const delLoading = ref(false)

const delData = async () => {
  const res = await delTicketsApi({
    ids: ids.value.map((o) => o.id).join(',')
  })
  if (res.code != '200') {
    return
  }
  getList()
}

const downImg = async () => {
  const images = !isBack.value ? viewerList.value[0] : viewerList.value[1]
  if (images.length == 0) {
    alert('没有图片可供下载')
    return
  }
  if (images.length > 1) {
    const zip = new JSZip()
    for (let i = 0; i < images.length; i++) {
      fetch(images[i])
        .then((response) => response.blob())
        .then((blob) => {
          zip.file(`img${i}.jpg`, blob)
          if (i === images.length - 1) {
            zip.generateAsync({ type: 'blob' }).then((content) => {
              saveAs(content, 'downloaded_images.zip')
            })
          }
        })
    }
  } else {
    fetch(images[0])
      .then((response) => response.blob())
      .then((blob) => {
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = 'image.jpg'
        link.click()
        document.body.removeChild(link)
      })
  }
}

const down = () => {
  fetch(PATH_URL + 'pdf', {
    method: 'GET'
  })
    .then((response) => response.blob())
    .then(async (blob) => {
      const formData = new FormData()
      formData.append(`files`, blob, `file.pdf`)
      formData.append(`pluginToken`, '2001259392@37')
      formData.append(`accountName`, '重庆卓堞商贸有限公司')
      const res = await axios({
        url: PATH_URL + 'plg/file/ocr',
        method: 'POST',
        data: formData,
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      if (res.data.code != '200') {
        alert('图片识别失败')
        return
      }
      var result = confirm('图片识别成功')
    })
}

const onExport = async () => {
  fetch(PATH_URL + '/tickets/excel', {
    method: 'GET'
  })
    .then((response) => response.blob())
    .then(async (blob) => {
      const a = document.createElement('a')
      a.style.display = 'none'
      document.body.appendChild(a)
      a.href = URL.createObjectURL(blob)
      console.log(URL.createObjectURL(blob))
      a.download = `票务 ${dayjs(new Date()).format('YYYY-MM-DD hh:mm:ss')}.xlsx`
      a.click()
      document.body.removeChild(a)
    })
}

const tableRowClassName = ({ row }: { row: any }) => {
  if (['6', '7', '8'].includes((row.tkNumber || '').slice(0, 1))) {
    return 'warning-row'
  }
  if (row.tkStatus.includes('保证待签收')) {
    return 'warning-row'
  }

  if (JSON.stringify(row.jgList).includes('包含当前户')) {
    return 'warning-row'
  }
  return ''
}
</script>

<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-danger);
  color: #fff;
}

.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
  background-color: var(--el-color-info-light-7);
}
</style>

<template>
  <div>
    <!-- <ContentWrap class="mb-4">
      <div class="flex items-center justify-end">
        <ElButton :icon="Tools" type="primary" @click="down">识别pdf </ElButton>
      </div>
    </ContentWrap> -->
    <ContentWrap class="mb-4">
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <div class="mr-10px"
            >已选<span class="c-red" style="font-weight: 700">{{ ids.length }}</span
            >条</div
          >
          <ElButton
            :disabled="ids.length <= 0"
            :loading="delLoading"
            type="danger"
            plain
            @click="delData()"
          >
            删除
          </ElButton>
        </div>
        <div class="flex items-center">
          <el-select v-model="searchParams.type" placeholder="筛选条件" style="width: 120px">
            <el-option
              v-for="item in [
                {
                  value: 1,
                  label: '承兑人'
                },
                {
                  value: 2,
                  label: '票号后六位'
                },
                {
                  value: 3,
                  label: '金额(万元)'
                },
                {
                  value: 4,
                  label: '识别时间'
                },
                {
                  value: 5,
                  label: '最后一手背书'
                }
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-date-picker
            v-if="searchParams.type == 4"
            v-model="searchParams.time"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY/MM/DD HH:mm:ss"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            style="max-width: 300px"
          />
          <el-input
            v-else
            v-model="searchParams.condition"
            style="width: 200px"
            placeholder="请输入内容"
            :prefix-icon="Search"
            clearable
          />
          <el-select
            class="ml-8"
            v-model="searchParams.accountName"
            placeholder="选择识别户"
            style="width: 180px"
            value-key="account"
            clearable
            multiple
            @change="selectChangeName"
          >
            <el-option
              v-for="item in nameOption"
              :key="item.id"
              :label="item.accountName"
              :value="item.id"
            />
          </el-select>
          <BaseButton :icon="refreshIcon" @click="getList" style="color: var(--el-color-primary)">
            查询
          </BaseButton>
        </div>
      </div>
    </ContentWrap>
    <ContentWrap>
      <div class="flex items-center justify-end mb-4">
        <ElButton :icon="Tools" type="primary" @click="dialogVisible = true">风险设置 </ElButton>
        <ElButton :icon="Tools" type="primary" @click="onExport">导出 </ElButton>
      </div>
      <Table
        :row-class-name="tableRowClassName"
        v-model:pageSize="pageSize"
        v-model:currentPage="currentPage"
        :columns="allSchemas.tableColumns"
        :showOverflowTooltip="false"
        :data="dataList"
        :loading="loading"
        row-key="id"
        :pagination="{
          total: total
        }"
        @register="tableRegister"
        @selection-change="tableSelectionChange"
      />
    </ContentWrap>

    <el-dialog
      destroy-on-close
      v-model="dialogVisible"
      title="风险设置"
      width="65%"
      style="background-color: #f5f7f9"
      draggable
    >
      <RiskSettingDialog @close="dialogVisible = false" />
    </el-dialog>
    <el-dialog v-model="viewerVisible" title="查看票面" width="60%">
      <template #header="{ titleId, titleClass }">
        <div class="flex items-center flex-1 justify-between mr-6">
          <h4 :id="titleId" :class="titleClass">查看票面({{ isBack ? '背面' : '正面' }})</h4>
          <div class="flex items-center">
            <el-button v-if="viewerList[1][0]" type="primary" @click="isBack = !isBack">
              切换
            </el-button>
            <el-button type="warning" @click="downImg()"> 下载 </el-button>
          </div>
        </div>
      </template>
      <div style="max-height: 80vh; overflow-y: scroll">
        <div v-if="!isBack" style="max-height: 84vh; overflow: hidden">
          <el-image
            id="copy1"
            v-for="url in viewerList[0]"
            :key="url"
            :src="url"
            style="width: 100%"
          />
        </div>
        <div v-else>
          <el-image
            id="copy2"
            v-for="url in viewerList[1]"
            :key="url"
            :src="url"
            style="width: 100%"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>
@/hooks/event/useEventBus
